package com.ldj.common;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import ahxu.commons.upload.DiskFileUploadEx;

public class Upload {
	
	public static HashMap upload(HttpServletRequest request, String uploaddir, String uploadType) throws IOException{
		HashMap map = new HashMap();
		String uploadDir = java.io.File.separator + uploaddir + java.io.File.separator;
		uploadDir = uploadDir.replace('/', java.io.File.separatorChar);
		if(!uploadDir.endsWith(File.separator)){		
			uploadDir = uploadDir + File.separatorChar;
		}
		java.io.File theLMSUploadDir = new java.io.File( request.getRealPath(uploadDir));
		if ( !theLMSUploadDir.isDirectory() )
		{
			theLMSUploadDir.mkdirs();
		}
		List fileItemList=null;
		DiskFileUploadEx fu = new DiskFileUploadEx();//初使化ahxu扩展后的组件
		fu.setAllowField(true);
		fu.setSizeMax(1000*1024*1024);//原有apache的upload:设置允许上传的最大值
		fu.setAllowFiles(uploadType);//设置允许的上传文件类型
		fu.setSizeThreshold(1024*1024);
		fu.setReportLimitSize(1024*1024);
		java.io.File tempDir = new java.io.File(uploadDir);
		if(!tempDir.isDirectory()){
			tempDir.mkdirs();
		}
		fu.setRepositoryPath(uploadDir);
		String zipfileName="";
		try{
			fileItemList=fu.parseRequestExSessionReport(request);//ahxu扩展后的:接收上传文件
			Iterator fileItemListIte=fileItemList.iterator();
	
			if(fileItemListIte.hasNext())
			{
				FileItem fileItem=(FileItem)fileItemListIte.next();
				//文件域的表单信息
				if (!fileItem.isFormField()) {
					String fileName = fileItem.getName();
					int index = fileName.lastIndexOf(".");
					String contentType = "";
			        if (index != -1) {
			        	contentType = fileName.substring(index, fileName.length());
			        }
					zipfileName = System.currentTimeMillis() + contentType;
					File savedFile = new File(request.getRealPath(uploadDir + zipfileName));
					fileItem.write(savedFile);
					map.put("fileName", zipfileName);
				}				
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		
		return map;
	}
	

}
